package cn.edu.jnu.x2020101323;

public class BowlingGame {

    private int[] rolls = new int[21];
    private int currentRoll = 0;   //第几个球

    //输入每次滚动中被击倒的瓶数（分数），并相应地更新 rolls 数组和 currentRoll 变量
    public void roll(int pins) {
        rolls[currentRoll++] = pins;
    }

    //根据保龄球规则计算游戏的总分
    public int score() {
        int score = 0;
        int rollIndex = 0;

        for (int frame = 0; frame < 10; frame++) {
            if (isStrike(rollIndex)) {
                score += 10 + strikeBonus(rollIndex);
                rollIndex++;
            } else if (isSpare(rollIndex)) {
                score += 10 + spareBonus(rollIndex);
                rollIndex += 2;
            } else {
                score += sumOfPinsInFrame(rollIndex);
                rollIndex += 2;
            }
        }

        return score;
    }

    //判断是否为全中
    private boolean isStrike(int rollIndex) {
        return rolls[rollIndex] == 10;
    }

    //判断是否为补中
    private boolean isSpare(int rollIndex) {
        return rolls[rollIndex] + rolls[rollIndex + 1] == 10;
    }

    //计算前两次投球的分数总和
    private int sumOfPinsInFrame(int rollIndex) {
        return rolls[rollIndex] + rolls[rollIndex + 1];
    }

    //计算全中时后面两次的分数
    private int strikeBonus(int rollIndex) {
        return rolls[rollIndex + 1] + rolls[rollIndex + 2];
    }

    //计算补中时后面一次的分数
    private int spareBonus(int rollIndex) {
        return rolls[rollIndex + 2];
    }

}
